package com.fzrskj.cloud.free.core.opitimize.session;

import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.winiis.component.common.utils.other.MapOperateUtils;
import org.apache.commons.collections.map.HashedMap;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * SessionServletUtils.
 *
 * @author zj.
 *         Created on 2019/2/25 0025.
 */
public class SessionServletUtils {
    private static String storeDataKey = "_value";
    private static String storeTimeKey = "_expire";
    /**
     * 设置 Session.
     * @param name session name.
     * @param value session value.
     */
    public static void set(String name, Object value) {
        HttpServletRequest request = CloudContextUtils.getHttpServletRequest();
        if (null != request) {
            request.getSession().setAttribute(name, value);
        }
    }

    /**
     * 设置 Session.
     * @param name session name.
     * @param value session value.
     * @param timeout timeout(unit: second).
     */
    public static void set(String name, Object value, Integer timeout) {
        Map<String, Object> data = new HashedMap();
        data.put(storeDataKey, value);
        data.put(storeTimeKey, timeout == 0 ? 0 :(System.currentTimeMillis() + (timeout * 1000)));

        HttpServletRequest request = CloudContextUtils.getHttpServletRequest();
        if (null != request) {
            request.getSession().setAttribute(name, data);
        }
    }

    /**
     * 获取Session.
     * @param name session name.
     * @param <T> target class.
     * @return T.
     */
    public static <T> T get(String name) {
        HttpServletRequest request = CloudContextUtils.getHttpServletRequest();
        if (null == request || null == request.getSession()) {
            return null;
        }

        Object value = request.getSession().getAttribute(name);
        if (null == value) {
            return null;
        }

        Map<String, Object> store = (Map) value;
        Long timeout = MapOperateUtils.getLong(store, storeTimeKey);
        if (timeout == 0 || timeout >= System.currentTimeMillis()) {
            Object data = store.get(storeDataKey);
            return (T) data;
        }

        return null;
    }
}
